<template>
  <view class="address-form">
    <view class="form">
      <view class="form-item">
        <text class="label">收货人</text>
        <input class="input" v-model="form.name" placeholder="请输入收货人姓名" />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input class="input" v-model="form.phone" type="number" placeholder="请输入手机号码" />
      </view>
      
      <view class="form-item" @click="showRegionPicker">
        <text class="label">所在地区</text>
        <view class="input">
          <text v-if="form.province">{{form.province}} {{form.city}} {{form.district}}</text>
          <text v-else class="placeholder">请选择所在地区</text>
        </view>
        <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
      </view>
      
      <view class="form-item">
        <text class="label">详细地址</text>
        <input class="input" v-model="form.detail" placeholder="请输入详细地址" />
      </view>
      
      <view class="form-item">
        <text class="label">设为默认地址</text>
        <switch class="switch" :checked="form.isDefault" @change="onDefaultChange" />
      </view>
    </view>
    
    <view class="submit-btn" @click="submit">
      <text>保存地址</text>
    </view>
    
    <!-- 地区选择器 -->
  
	<uni-popup ref="regionPopup" background-color="#fff"  border-radius="10px 10px 0 0" type="bottom">
		 <view class="region-picker">
        <view class="picker-header">
          <text class="cancel" @click="cancelRegionPicker">取消</text>
          <text class="title">选择地区</text>
          <text class="confirm" @click="confirmRegionPicker">确定</text>
        </view>
        <picker-view class="picker" :value="pickerValue" @change="onRegionChange">
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in provinces" :key="index">{{item.name}}</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in cities" :key="index">{{item.name}}</view>
          </picker-view-column>
          <picker-view-column>
            <view class="picker-item" v-for="(item, index) in districts" :key="index">{{item.name}}</view>
          </picker-view-column>
        </picker-view>
      </view>
	</uni-popup>
  </view>
</template>

<script>
  import provinces from '@/common/region/provinces.js'
  import cities from '@/common/region/cities.js'
  import districts from '@/common/region/districts.js'
  
  export default {
    data() {
      return {
        form: {
          id: '',
          name: '',
          phone: '',
          province: '',
          city: '',
          district: '',
          detail: '',
          isDefault: false
        },
        provinces: provinces,
        cities: [],
        districts: [],
        pickerValue: [0, 0, 0],
        tempRegion: {
          province: '',
          city: '',
          district: ''
        }
      }
    },
    onLoad(options) {
      if (options.type === 'edit' && options.id) {
        this.getAddressDetail(options.id)
        uni.setNavigationBarTitle({
          title: '编辑地址'
        })
      } else {
        uni.setNavigationBarTitle({
          title: '添加地址'
        })
      }
    },
    methods: {
      // 获取地址详情
      getAddressDetail(id) {
        // 实际项目中这里应该请求接口获取地址详情
        // 这里模拟数据
        const address = {
          id: id,
          name: '张三',
          phone: '13800138000',
          province: '广东省',
          city: '深圳市',
          district: '南山区',
          detail: '科技园路1号',
          isDefault: true
        }
        this.form = {...address}
        
        // 设置地区选择器的初始值
        this.setRegionPickerValue(address.province, address.city, address.district)
      },
      
      // 设置地区选择器的初始值
      setRegionPickerValue(province, city, district) {
        // 查找省份索引
        const provinceIndex = this.provinces.findIndex(item => item.name === province)
        if (provinceIndex === -1) return
        
        // 设置城市数据
        const provinceCode = this.provinces[provinceIndex].code
        this.cities = cities[provinceCode] || []
        
        // 查找城市索引
        const cityIndex = this.cities.findIndex(item => item.name === city)
        if (cityIndex === -1) return
        
        // 设置区县数据
        const cityCode = this.cities[cityIndex].code
        this.districts = districts[cityCode] || []
        
        // 查找区县索引
        const districtIndex = this.districts.findIndex(item => item.name === district)
        if (districtIndex === -1) return
        
        // 设置pickerValue
        this.pickerValue = [provinceIndex, cityIndex, districtIndex]
      },
      
      // 显示地区选择器
      showRegionPicker() {
        this.tempRegion = {
          province: this.form.province,
          city: this.form.city,
          district: this.form.district
        }
        this.$refs.regionPopup.open()
      },
      
      // 地区选择器变化
      onRegionChange(e) {
        const value = e.detail.value
        this.pickerValue = value
        
        // 更新城市和区县数据
        const provinceCode = this.provinces[value[0]].code
        this.cities = cities[provinceCode] || []
        
        if (this.cities.length > 0) {
          const cityCode = this.cities[value[1]]?.code
          this.districts = districts[cityCode] || []
        } else {
          this.districts = []
        }
      },
      
      // 取消地区选择
      cancelRegionPicker() {
        this.$refs.regionPopup.close()
      },
      
      // 确认地区选择
      confirmRegionPicker() {
        const [provinceIndex, cityIndex, districtIndex] = this.pickerValue
        
        this.form.province = this.provinces[provinceIndex].name
        this.form.city = this.cities[cityIndex]?.name || ''
        this.form.district = this.districts[districtIndex]?.name || ''
        
        this.$refs.regionPopup.close()
      },
      
      // 默认地址切换
      onDefaultChange(e) {
        this.form.isDefault = e.detail.value
      },
      
      // 提交表单
      submit() {
        if (!this.validateForm()) return
        
        if (this.form.id) {
          this.updateAddress()
        } else {
          this.addAddress()
        }
      },
      
      // 验证表单
      validateForm() {
        if (!this.form.name) {
          uni.showToast({
            title: '请输入收货人姓名',
            icon: 'none'
          })
          return false
        }
        
        if (!this.form.phone) {
          uni.showToast({
            title: '请输入手机号码',
            icon: 'none'
          })
          return false
        }
        
        if (!/^1[3-9]\d{9}$/.test(this.form.phone)) {
          uni.showToast({
            title: '请输入正确的手机号码',
            icon: 'none'
          })
          return false
        }
        
        if (!this.form.province || !this.form.city || !this.form.district) {
          uni.showToast({
            title: '请选择所在地区',
            icon: 'none'
          })
          return false
        }
        
        if (!this.form.detail) {
          uni.showToast({
            title: '请输入详细地址',
            icon: 'none'
          })
          return false
        }
        
        return true
      },
      
      // 添加地址
      addAddress() {
        // 实际项目中这里应该调用添加地址接口
        const newAddress = {
          ...this.form,
          id: Date.now().toString() // 模拟生成ID
        }
        
        // 模拟添加到地址列表
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        prevPage.$vm.addressList.unshift(newAddress)
        
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      },
      
      // 更新地址
      updateAddress() {
        // 实际项目中这里应该调用更新地址接口
        const updatedAddress = {...this.form}
        
        // 模拟更新地址列表
        const pages = getCurrentPages()
        const prevPage = pages[pages.length - 2]
        const index = prevPage.$vm.addressList.findIndex(item => item.id === this.form.id)
        if (index !== -1) {
          prevPage.$vm.addressList.splice(index, 1, updatedAddress)
        }
        
        uni.showToast({
          title: '更新成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    }
  }
</script>

<style scoped>
  .address-form {
    height: 100vh;
    background-color: #f5f5f5;
  }
  
  .form {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 10rpx;
    padding: 0 20rpx;
  }
  
  .form-item {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1rpx solid #eee;
  }
  
  .form-item:last-child {
    border-bottom: none;
  }
  
  .label {
    width: 160rpx;
    font-size: 28rpx;
    color: #333;
  }
  
  .input {
    flex: 1;
    font-size: 28rpx;
    color: #333;
  }
  
  .placeholder {
    color: #999;
  }
  
  .switch {
    transform: scale(0.8);
  }
  
  .submit-btn {
    height: 90rpx;
    line-height: 90rpx;
    text-align: center;
    background-color: #1296db;
    color: #fff;
    font-size: 30rpx;
    margin: 40rpx 20rpx;
    border-radius: 45rpx;
  }
  
  .region-picker {
    background-color: #fff;
    height: 600rpx;
  }
  
  .picker-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    padding: 0 30rpx;
    border-bottom: 1rpx solid #eee;
  }
  
  .cancel, .confirm {
    font-size: 28rpx;
    color: #1296db;
  }
  
  .title {
    font-size: 32rpx;
    font-weight: bold;
  }
  
  .picker {
    height: 520rpx;
  }
  
  .picker-item {
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: 28rpx;
  }
</style>